<template>
	<div class="editable-cell">
		<!-- 编辑模式 -->
		<div v-if="isEditing" class="editing-cell" ref="editorCellRef">
			<!-- 编辑器插槽 -->
			<slot name="editor" :value="currentValue" :save="saveEdit" :cancel="cancelEdit"
				:on-change="handleValueChange">
				<!-- 默认编辑器 -->
				<div class="default-editor">
					<el-input ref="defaultInputRef" v-model="currentValue"
						:class="{'edit-input': true, 'has-error': hasError}" @blur="handleBlur"
						@keydown.enter="saveEdit" @keydown.esc="cancelEdit" />
				</div>
			</slot>

			<!-- 错误信息展示 -->
			<div v-if="hasError" class="error-message">{{ errorMessage }}</div>
		</div>

		<!-- 显示模式 -->
		<div v-else class="display-cell" @click="handleEdit">
			<slot> </slot>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'TaEditableCell',
		props: {
			// 单元格的值
			value: {
				type: [String, Number, Object, Array, Boolean],
				default: ''
			},
			// 自定义验证函数
			validator: {
				type: Function,
				default: null
			},
			// 是否可编辑
			editable: {
				type: Boolean,
				default: true
			},
			// 自动保存
			autoSave: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				isEditing: false,
				currentValue: null,
				hasError: false,
				errorMessage: ''
			}
		},
		watch: {
			value: {
				immediate: true,
				handler(newVal) {
					// 深拷贝值，避免直接修改prop
					this.currentValue = this.deepCopy(newVal);
				}
			}
		},
		methods: {
			// 深拷贝函数
			deepCopy(value) {
				if (value === null || typeof value !== 'object') {
					return value;
				}
				return JSON.parse(JSON.stringify(value));
			},
			// 获取插槽中第一个元素
			slotAutoFocus() {
				const wrapper = this.$refs.editorCellRef;
				if (wrapper && wrapper.children.length) {
					const el = wrapper.children[0];
					const instance = el.__vueParentComponent?.proxy || el.__vnode?.component?.proxy;

					if (typeof instance.toggleMenu === 'function') {
						instance.toggleMenu();
						return true;
					}

					if (typeof instance.focus === 'function') {
						instance.focus();
						return true;
					}

					// 检查是否有内部组件引用
					if (instance.$refs && instance.$refs.input && typeof instance.$refs.input.focus === 'function') {
						instance.$refs.input.focus();
						return true;
					}

					// 检查是否有inputRef (Vue 3常见模式)
					if (instance.inputRef && typeof instance.inputRef.focus === 'function') {
						instance.inputRef.focus();
						return true;
					}

					// 直接查找DOM
					const inputElement = el.querySelector('input');
					if (inputElement) {
						inputElement.focus();
						return true;
					}

					console.error("slotAutoFocus 没找见元素", instance)
				}
			},
			// 进入编辑模式
			handleEdit() {
				if (!this.editable) return;
				this.isEditing = true;
				this.hasError = false;
				this.$nextTick(() => {
					this.slotAutoFocus();
					this.$emit('edit-start', this.currentValue);
				});
			},

			// 处理值变化
			handleValueChange(value) {
				this.currentValue = value;
			},

			// 失焦时保存
			handleBlur() {
				if (this.autoSave) {
					this.saveEdit();
				}
			},

			// 保存编辑
			saveEdit() {
				if (this.validator) {
					const validResult = this.validator(this.currentValue);
					if (validResult !== true) {
						this.hasError = true;
						this.errorMessage = typeof validResult === 'string' ? validResult : '输入内容无效';
						return;
					}
				}

				this.$emit('input', this.currentValue);
				this.$emit('change', this.currentValue);
				this.$emit('edit-end', this.currentValue);
				this.isEditing = false;
				this.hasError = false;
			},

			// 取消编辑
			cancelEdit() {
				this.currentValue = this.deepCopy(this.value);
				this.isEditing = false;
				this.hasError = false;
				this.$emit('edit-cancel');
			}
		}
	}
</script>

<style scoped>
	.editable-cell {
		position: relative;
	}

	.display-cell {
		padding: 5px;
		cursor: pointer;
		min-height: 24px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.display-cell:hover .edit-icon {
		visibility: visible;
	}

	.edit-icon {
		margin-left: 5px;
		visibility: hidden;
		color: #409EFF;
	}

	.default-display {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.editing-cell {
		padding: 0;
	}

	.default-editor {
		width: 100%;
	}

	.edit-input {
		width: 100%;
		border: 1px solid #dcdfe6;
		border-radius: 4px;
		padding: 5px;
		outline: none;
		box-sizing: border-box;
	}

	.edit-input:focus {
		border-color: #409EFF;
	}

	.has-error {
		border-color: #F56C6C !important;
	}

	.error-message {
		color: #F56C6C;
		font-size: 12px;
		margin-top: 2px;
	}
</style>
